package com.app.teaware.goods;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.app.teaware.R;
import com.app.teaware.basis.BasisActivity;
import com.app.teaware.bean.BaseListData;
import com.app.teaware.bean.BaseListDataListBean;
import com.app.teaware.util.HexUtil;
import com.nlscan.android.uhf.TagInfo;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

public class GoodsTestActivity extends BasisActivity {

    /**读码结果发送的广播action*/
    public final static String ACTION_UHF_RESULT_SEND = "nlscan.intent.action.uhf.ACTION_RESULT";
    /**读码结果发送的广播Extra*/
    public final static String EXTRA_TAG_INFO = "tag_info";

    @BindView(R.id.recyclerview)
    RecyclerView mRecyclerView;
    BaseListDataListBean listBean;

    private String[] Coname = new String[] { "序号", "EPC ID", "次数", "天线", "协议", "RSSI", "频率", "附加数据" };//表头
    MyAdapterList adapter;


    @Override
    public void initViews() {
        super.initViews();
        setContentView(R.layout.base_recycler_with_top);
        setTitle("盘点测试 ");
        setTitleLeftButton(null);
        LinearLayoutManager layoutManager = new LinearLayoutManager(mContext);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(layoutManager);
    }


    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        listBean = new BaseListDataListBean();
        adapter = new MyAdapterList();
        mRecyclerView.setAdapter(adapter);

    }



    private BroadcastReceiver mResultReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent)
        {
            String action = intent.getAction();
            if(!ACTION_UHF_RESULT_SEND.equals(action))
                return ;
            Parcelable[] tagInfos =  intent.getParcelableArrayExtra(EXTRA_TAG_INFO);
            assesResult(tagInfos);
        }//end onReceiver
    };

      Map<String, TagInfo> TagsMap = new LinkedHashMap<String, TagInfo>();// 有序

    private void assesResult(Parcelable[] tagInfos) {
        if(tagInfos != null && tagInfos.length > 0) {

            for(int i =0 ;i < tagInfos.length; i++) {
                TagInfo tag = (TagInfo) tagInfos[i];
                String epcId = HexUtil.bytesToHexString(tag.EpcId);
                if (!TagsMap.containsKey(epcId)) {
                    TagsMap.put(epcId, tag);

                    // show
                    Map<String, String> m = new HashMap<String, String>();
                    listBean.getList().add(new BaseListData(""+Coname[0], ""+String.valueOf(TagsMap.size())));

                    String epcstr =epcId;
                    if (epcstr.length() < 24)
                        epcstr = String.format("%-24s", epcstr);

                    listBean.getList().add(new BaseListData(""+Coname[1], ""+epcstr));

                    String cs = m.get("次数");
                    if (cs == null)
                        cs = "0";
                    int isc = Integer.parseInt(cs) + tag.ReadCnt;

                    listBean.getList().add(new BaseListData(""+Coname[2], ""+String.valueOf(isc)));
                    listBean.getList().add(new BaseListData(""+Coname[3], ""+String.valueOf(tag.AntennaID)));
                    listBean.getList().add(new BaseListData(""+Coname[4], ""));
                    listBean.getList().add(new BaseListData(""+Coname[5], ""+String.valueOf(tag.RSSI)));
                    listBean.getList().add(new BaseListData(""+Coname[6], ""+String.valueOf(tag.Frequency)));

                    if (tag.EmbededDatalen > 0) {
                        String out = HexUtil.bytesToHexString(tag.EmbededData);
                        listBean.getList().add(new BaseListData(""+Coname[7], ""+String.valueOf(out)));

                    } else{
                        listBean.getList().add(new BaseListData(""+Coname[7], ""));
                    }
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }



    public class MyAdapterList extends RecyclerView.Adapter<MyAdapterList.ViewHolder> {


        public MyAdapterList() {

        }

        //创建新View，被LayoutManager所调用
        @Override
        public ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
            View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.base_list_info_list_item_child, viewGroup, false);
            return new ViewHolder(view);
        }

        //将数据与界面进行绑定的操作
        @Override
        public void onBindViewHolder(ViewHolder viewHolder, int position) {
            viewHolder.bind(position);
        }

        //获取数据的数量
        @Override
        public int getItemCount() {
            int count = listBean == null ? 0 : listBean.getList().size();
            return count;
        }

        //自定义的ViewHolder，持有每个Item的的所有界面元素
        public class ViewHolder extends RecyclerView.ViewHolder {
            @BindView(R.id.text_name)
            TextView text_name;
            @BindView(R.id.text_value)
            TextView text_value;

            public ViewHolder(View view) {
                super(view);
                ButterKnife.bind(this, view);
            }

            public void bind(int position) {
                BaseListData data = listBean.getList().get(position);
                text_name.setText("" + data.getId());
                text_value.setText("" + data.getName() == null ? "" : data.getName());
            }
        }
    }


    @Override
    protected void onPause() {
        super.onPause();
        unRegisterResultReceiver();
    }


    @Override
    protected void onResume() {
        super.onResume();
        registerResultReceiver();
    }

    private void registerResultReceiver() {
        try {
            IntentFilter iFilter = new IntentFilter(ACTION_UHF_RESULT_SEND);
            mContext.registerReceiver(mResultReceiver, iFilter);
        } catch (Exception e) {
        }

    }

    private void unRegisterResultReceiver() {
        try {
            mContext.unregisterReceiver(mResultReceiver);
        } catch (Exception e) {
        }

    }
}
